package com.witmore.neutron.ai.mcp.server.trading.service;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.witmore.neutron.ai.mcp.server.trading.dto.StockAnalysisReportDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.format.DateTimeFormatter;

/**
 * PDF报告生成服务
 * 
 * @author 豆子高
 * @date 2025-01-20
 */
@Slf4j
@Service
public class PdfReportService {

    @Autowired
    private AbnormalPdfReportService abnormalPdfReportService;

    /**
     * 生成股票分析报告PDF
     * 
     * @param report 分析报告数据
     * @return PDF字节数组
     */
    public byte[] generateStockAnalysisReportPdf(StockAnalysisReportDTO report) throws IOException {
        log.info("开始生成PDF报告 - 股票代码: {}", report.getStockCode());

        // 生成HTML内容
        String htmlContent = generateHtmlContent(report);

        // 转换为PDF
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        
        // 配置转换属性
        ConverterProperties properties = new ConverterProperties();
        DefaultFontProvider fontProvider = new DefaultFontProvider(true, true, true);
        properties.setFontProvider(fontProvider);
        properties.setCharset("UTF-8");

        try {
            HtmlConverter.convertToPdf(htmlContent, outputStream, properties);
            log.info("PDF报告生成成功 - 股票代码: {}, 文件大小: {} bytes", 
                    report.getStockCode(), outputStream.size());
            return outputStream.toByteArray();
        } catch (Exception e) {
            log.error("PDF生成失败 - 股票代码: {}, 错误: {}", report.getStockCode(), e.getMessage(), e);
            throw new IOException("PDF生成失败: " + e.getMessage(), e);
        } finally {
            outputStream.close();
        }
    }

    /**
     * 生成股票分析报告PDF（增强版）
     * 使用增强的AbnormalPdfReportService生成更丰富的财务分析报告
     * 
     * @param report 分析报告数据
     * @param userId 用户ID（可选，用于记录）
     * @return PDF字节数组
     */
    public byte[] generateEnhancedStockAnalysisReportPdf(StockAnalysisReportDTO report, Long userId) throws IOException {
        log.info("开始生成增强版PDF报告 - 股票代码: {}, 用户ID: {}", report.getStockCode(), userId);

        try {
            // 使用增强的PDF报告服务生成更丰富的财务分析报告
            return abnormalPdfReportService.generateFinancialAnalysisReportPdf(userId, report);
        } catch (Exception e) {
            log.warn("使用增强版PDF生成失败，回退到简化版本 - 股票代码: {}, 错误: {}", 
                    report.getStockCode(), e.getMessage());
            // 回退到原有的简化版本
            return generateStockAnalysisReportPdf(report);
        }
    }

    /**
     * 生成HTML内容
     */
    private String generateHtmlContent(StockAnalysisReportDTO report) {
        StringBuilder html = new StringBuilder();
        
        // HTML头部和样式
        html.append("<!DOCTYPE html>")
            .append("<html lang=\"zh-CN\">")
            .append("<head>")
            .append("<meta charset=\"UTF-8\">")
            .append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">")
            .append("<title>股票分析报告</title>")
            .append("<style>")
            .append(getReportStyles())
            .append("</style>")
            .append("</head>")
            .append("<body>");

        // 报告标题
        html.append("<div class=\"header\">")
            .append("<h1>股票异动分析报告</h1>")
            .append("<div class=\"stock-info\">")
            .append("<span class=\"stock-code\">").append(report.getStockCode()).append("</span>");
        
        if (StringUtils.hasText(report.getStockName())) {
            html.append("<span class=\"stock-name\">").append(report.getStockName()).append("</span>");
        }
        
        html.append("</div>")
            .append("<div class=\"analysis-time\">分析时间: ");
        
        if (report.getAnalysisTime() != null) {
            html.append(report.getAnalysisTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
        } else {
            html.append(java.time.LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
        }
        
        html.append("</div>")
            .append("</div>");

        // 核心结论
        html.append("<div class=\"summary-section\">")
            .append("<h2>🎯 核心结论</h2>")
            .append("<div class=\"summary-grid\">");

        if (report.getOverallScore() != null) {
            String scoreClass = getScoreClass(report.getOverallScore());
            html.append("<div class=\"summary-item\">")
                .append("<span class=\"label\">综合评分</span>")
                .append("<span class=\"value ").append(scoreClass).append("\">")
                .append(report.getOverallScore()).append("/100分</span>")
                .append("</div>");
        }

        if (report.getRiskLevel() != null) {
            String riskClass = getRiskClass(report.getRiskLevel());
            html.append("<div class=\"summary-item\">")
                .append("<span class=\"label\">风险等级</span>")
                .append("<span class=\"value ").append(riskClass).append("\">")
                .append(report.getRiskLevel()).append("级</span>")
                .append("</div>");
        }

        if (StringUtils.hasText(report.getInvestmentRecommendation())) {
            String recommendationClass = getRecommendationClass(report.getInvestmentRecommendation());
            html.append("<div class=\"summary-item\">")
                .append("<span class=\"label\">投资建议</span>")
                .append("<span class=\"value ").append(recommendationClass).append("\">")
                .append(report.getInvestmentRecommendation()).append("</span>")
                .append("</div>");
        }

        html.append("</div>");

        if (StringUtils.hasText(report.getRecommendationReason())) {
            html.append("<div class=\"recommendation-reason\">")
                .append("<strong>建议理由:</strong> ").append(report.getRecommendationReason())
                .append("</div>");
        }

        html.append("</div>");

        // 各类分析内容
        // 基本面分析已整合到财务分析中
        appendAnalysisSection(html, "💰 财务分析", report.getFinancialAnalysis());
        // 新闻分析已移除，专注财务报表分析
        appendAnalysisSection(html, "📈 研报分析", report.getResearchAnalysis());

        // 风险提示
        if (report.getRiskLevel() != null && StringUtils.hasText(report.getRiskDescription())) {
            html.append("<div class=\"risk-section\">")
                .append("<h2>⚠️ 风险提示</h2>")
                .append("<div class=\"risk-content\">")
                .append("<p><strong>风险等级:</strong> ").append(report.getRiskLevel()).append("级</p>")
                .append("<p><strong>风险描述:</strong> ").append(report.getRiskDescription()).append("</p>")
                .append("</div>")
                .append("</div>");
        }

        // 目标价格
        if (StringUtils.hasText(report.getTargetPriceRange())) {
            html.append("<div class=\"target-price-section\">")
                .append("<h2>🎯 目标价格</h2>")
                .append("<div class=\"target-price-content\">")
                .append(report.getTargetPriceRange())
                .append("</div>")
                .append("</div>");
        }

        // AI总结
        if (StringUtils.hasText(report.getAiSummary())) {
            html.append("<div class=\"ai-summary-section\">")
                .append("<h2>🤖 AI综合总结</h2>")
                .append("<div class=\"ai-summary-content\">")
                .append(convertMarkdownToHtml(report.getAiSummary()))
                .append("</div>")
                .append("</div>");
        }

        // 页脚
        html.append("<div class=\"footer\">")
            .append("<p><strong>免责声明:</strong> 本分析报告仅供参考，不构成投资建议。投资者应基于自身情况做出独立判断。</p>")
            .append("<p>报告生成时间: ").append(java.time.LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))).append("</p>")
            .append("</div>");

        html.append("</body></html>");

        return html.toString();
    }

    /**
     * 添加分析章节
     */
    private void appendAnalysisSection(StringBuilder html, String title, String content) {
        if (StringUtils.hasText(content)) {
            html.append("<div class=\"analysis-section\">")
                .append("<h2>").append(title).append("</h2>")
                .append("<div class=\"analysis-content\">")
                .append(convertMarkdownToHtml(content))
                .append("</div>")
                .append("</div>");
        }
    }

    /**
     * 优化的Markdown到HTML转换
     */
    private String convertMarkdownToHtml(String markdown) {
        if (markdown == null || markdown.trim().isEmpty()) {
            return "";
        }
        
        // 预处理：处理空行和换行
        String processed = markdown.trim()
                .replaceAll("\\r\\n", "\n") // 统一换行符
                .replaceAll("\\r", "\n");   // 统一换行符
        
        // 按段落分割
        String[] paragraphs = processed.split("\\n\\s*\\n");
        StringBuilder result = new StringBuilder();
        
        for (String paragraph : paragraphs) {
            if (paragraph.trim().isEmpty()) {
                continue;
            }
            
            String processedParagraph = paragraph.trim()
                    .replaceAll("\\*\\*([^*\n]+)\\*\\*", "<strong>$1</strong>") // 粗体
                    .replaceAll("\\*([^*\n]+)\\*", "<em>$1</em>") // 斜体
                    .replaceAll("### ([^\n]+)", "<h4>$1</h4>") // h4标题
                    .replaceAll("## ([^\n]+)", "<h3>$1</h3>") // h3标题
                    .replaceAll("# ([^\n]+)", "<h2>$1</h2>") // h2标题
                    .replaceAll("\\n", "<br>"); // 段内换行
            
            // 如果是标题，不包装在p标签中
            if (processedParagraph.startsWith("<h")) {
                result.append(processedParagraph);
            } else {
                result.append("<p>").append(processedParagraph).append("</p>");
            }
        }
        
        return result.toString();
    }

    /**
     * 获取评分样式类
     */
    private String getScoreClass(Integer score) {
        if (score >= 80) return "score-excellent";
        if (score >= 60) return "score-good";
        if (score >= 40) return "score-average";
        return "score-poor";
    }

    /**
     * 获取风险等级样式类
     */
    private String getRiskClass(Integer riskLevel) {
        if (riskLevel <= 2) return "risk-low";
        if (riskLevel <= 3) return "risk-medium";
        return "risk-high";
    }

    /**
     * 获取投资建议样式类
     */
    private String getRecommendationClass(String recommendation) {
        if ("买入".equals(recommendation)) return "rec-buy";
        if ("持有".equals(recommendation)) return "rec-hold";
        return "rec-sell";
    }

    /**
     * 获取报告样式
     */
    private String getReportStyles() {
        return """
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            
            body {
                font-family: "Microsoft YaHei", "PingFang SC", "Hiragino Sans GB", "SimSun", Arial, sans-serif;
                line-height: 1.6;
                color: #333;
                background-color: #fff;
                padding: 20px;
                font-size: 14px;
            }
            
            .header {
                text-align: center;
                margin-bottom: 30px;
                padding-bottom: 20px;
                border-bottom: 2px solid #2c5282;
            }
            
            .header h1 {
                color: #2c5282;
                font-size: 28px;
                margin-bottom: 10px;
            }
            
            .stock-info {
                margin: 10px 0;
            }
            
            .stock-code {
                font-size: 20px;
                font-weight: bold;
                color: #e53e3e;
                margin-right: 10px;
            }
            
            .stock-name {
                font-size: 18px;
                color: #2d3748;
            }
            
            .analysis-time {
                color: #718096;
                font-size: 14px;
            }
            
            .summary-section {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                padding: 20px;
                border-radius: 10px;
                margin-bottom: 30px;
            }
            
            .summary-section h2 {
                margin-bottom: 15px;
                font-size: 22px;
            }
            
            .summary-grid {
                display: flex;
                flex-wrap: wrap;
                gap: 20px;
                justify-content: space-around;
            }
            
            .summary-item {
                text-align: center;
                flex: 1;
                min-width: 150px;
            }
            
            .summary-item .label {
                display: block;
                font-size: 14px;
                opacity: 0.9;
                margin-bottom: 5px;
            }
            
            .summary-item .value {
                display: block;
                font-size: 20px;
                font-weight: bold;
            }
            
            .recommendation-reason {
                margin-top: 15px;
                padding: 15px;
                background: rgba(255,255,255,0.1);
                border-radius: 5px;
                border-left: 4px solid #ffd700;
            }
            
            .analysis-section {
                margin-bottom: 30px;
                padding: 20px;
                border: 1px solid #e2e8f0;
                border-radius: 8px;
                background: #f7fafc;
            }
            
            .analysis-section h2 {
                color: #2d3748;
                font-size: 20px;
                margin-bottom: 15px;
                border-bottom: 2px solid #4299e1;
                padding-bottom: 5px;
            }
            
            .analysis-content {
                line-height: 1.8;
            }
            
            .analysis-content h3 {
                color: #2d3748;
                font-size: 16px;
                margin: 15px 0 8px 0;
            }
            
            .analysis-content p {
                margin-bottom: 10px;
            }
            
            .risk-section {
                background: #fed7d7;
                border: 1px solid #feb2b2;
                border-radius: 8px;
                padding: 20px;
                margin-bottom: 30px;
            }
            
            .risk-section h2 {
                color: #c53030;
                margin-bottom: 15px;
            }
            
            .risk-content {
                color: #742a2a;
            }
            
            .target-price-section {
                background: #c6f6d5;
                border: 1px solid #9ae6b4;
                border-radius: 8px;
                padding: 20px;
                margin-bottom: 30px;
            }
            
            .target-price-section h2 {
                color: #276749;
                margin-bottom: 15px;
            }
            
            .target-price-content {
                color: #22543d;
                font-size: 16px;
            }
            
            .ai-summary-section {
                background: #e6fffa;
                border: 1px solid #81e6d9;
                border-radius: 8px;
                padding: 20px;
                margin-bottom: 30px;
            }
            
            .ai-summary-section h2 {
                color: #234e52;
                margin-bottom: 15px;
            }
            
            .ai-summary-content {
                color: #285e61;
            }
            
            .footer {
                margin-top: 40px;
                padding-top: 20px;
                border-top: 1px solid #e2e8f0;
                text-align: center;
                color: #718096;
                font-size: 12px;
            }
            
            /* 数值样式 */
            .score-excellent { color: #38a169; }
            .score-good { color: #3182ce; }
            .score-average { color: #d69e2e; }
            .score-poor { color: #e53e3e; }
            
            .risk-low { color: #38a169; }
            .risk-medium { color: #d69e2e; }
            .risk-high { color: #e53e3e; }
            
            .rec-buy { color: #38a169; }
            .rec-hold { color: #3182ce; }
            .rec-sell { color: #e53e3e; }
            
            /* PDF专用样式优化 */
            .analysis-content p {
                margin-bottom: 12px;
                text-indent: 0;
            }
            
            .analysis-content h3 {
                margin-top: 20px;
                margin-bottom: 10px;
                page-break-after: avoid;
            }
            
            .summary-grid {
                page-break-inside: avoid;
            }
            
            .analysis-section {
                page-break-inside: avoid;
                break-inside: avoid;
            }
            
            /* 确保文字清晰显示 */
            * {
                -webkit-font-smoothing: antialiased;
                -moz-osx-font-smoothing: grayscale;
            }
            
            @media print {
                body { 
                    padding: 10px; 
                    font-size: 12px;
                }
                .summary-section { 
                    background: #f0f0f0 !important; 
                    color: #333 !important; 
                    -webkit-print-color-adjust: exact;
                    color-adjust: exact;
                }
                
                .header h1 {
                    font-size: 24px;
                }
                
                h2 {
                    font-size: 18px;
                }
                
                h3 {
                    font-size: 16px;
                }
            }
            """;
    }
}
